import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { fileURLToPath, URL } from 'node:url'
import { createHtmlPlugin } from 'vite-plugin-html'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import tailwindcss from '@tailwindcss/vite'
// import legacy from '@vitejs/plugin-legacy'
import fs from 'fs'

const htmlTemplateDirName = 'html-template'
/**
 * 创建HTML，根据构建目标不同 读取不同main.js
 * target 构建目标
 * envData 环境变量
 */
const createHTML = (target, envData) => {
  fs.copyFileSync(
    path.resolve(__dirname, `${htmlTemplateDirName}/${target || 'index'}.html`),
    path.resolve(__dirname, `index.html`)
  )
  return createHtmlPlugin({
    entry: target ? `/src/${target}/main.js` : '/src/main.js',
    template: `index.html`,
    inject: {
      // html注入变量
      data: {
        title: target || '我的Vite项目',
      },
    },
    outputPath: '/',
  })
}

// 构建完成后 移动index.html
const moveIndex = (outDir) => {
  return {
    name: 'my-vite-plugin', // 必须的插件名称，用于调试和错误报告等。
    closeBundle() {
      fs.rmSync(path.resolve(__dirname, `index.html`))
    },
  }
}

export default defineConfig(({ mode }) => {
  const envDir = './config'
  const envDefault = loadEnv('development', path.resolve(__dirname, envDir)) // 获取默认配置
  const envCurrent = loadEnv(mode, path.resolve(__dirname, envDir)) // 获取 .env.xxx 文件里定义的环境变量
  const env = Object.assign({}, envDefault, envCurrent)

  const vitem_build_target = process.env.VUE_BUILD_TARGET
  // 打包输出路径,默认dist，根据VUE_BUILD_TARGET 区分
  const outDir = path.resolve(
    __dirname,
    `build/${vitem_build_target ? `__${vitem_build_target}` : 'dist'}`
  )
  const temp = {
    base: './',
    plugins: [
      vue(),
      createHTML(vitem_build_target, env),
      AutoImport({
        // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
        imports: ['vue'],
      }),
      Components({
        resolvers: [AntDesignVueResolver({ importStyle: 'less', resolveIcons: true })],
      }),
      // legacy({
      //   targets: ['defaults', 'not IE 11'],
      //   additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
      // }),
      // moveIndex(outDir),
      tailwindcss(), // 支持tailwindcss
    ],
    css: {
      preprocessorOptions: {
        // 基础配置（无全局注入时可为空）
        scss: {
          additionalData: `
            @use "@/assets/style/tool.scss" as tool; // 引入自定义方法 命名空间tool
          `,
        },
      },
    },
    envDir,
    root: process.cwd(),
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    build: {
      outDir,
      rollupOptions: {
        input: {
          main: path.resolve(__dirname, `index.html`),
        },
        output: {
          entryFileNames: `assets/js/[name]-[hash].js`,
          chunkFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
        },
        plugins: [
          {
            name: `${vitem_build_target}`,
            buildEnd() {},
          },
        ],
      },
    },
  }
  return temp
})
